<?

require_once("mysql.php");
require_once("captcha.php");
require_once("reference.php");
require_once("location.php");
require_once("utilities.php");


function find_or_create_local_seller_image($im) {

    $rval = NULL;

    if (starts_with($im, "images/")) {
        if (trim($im) == "images/null.png" || trim($im) == "images/no.png") {
            return "images/n.png";
        }
    }

    if (starts_with($im, "logo/")) return $im;
 
    $r = MYSQL_Q("SELECT * FROM photo WHERE original='".$im."'");
    $c = mysql_num_rows($r);

    if ($c == 0) {

        do {
            $absolute = "../logo/".rstring(12);
        } while (@file_exists($absolute));

        $image = @file_get_contents($im);

        if (!$image) {
            echo '["Image link for <strong>'.$_POST['seller'].'</strong> broken"]'; die();
        }

        if (!@file_put_contents($absolute, $image)) {
            echo '["Error: 0x0004"]'; die();
        }

        $relative = substr($absolute, 3);

        MYSQL_Q("INSERT INTO photo VALUES ('".$relative."', '".$im."', 2, 1)");

        $rval = $relative;

    } else {

        $row = mysql_fetch_assoc($r);
        MYSQL_Q("UPDATE photo SET count=count+1 WHERE original='".$im."'");
        $rval = $row['path'];

    }

    return $rval;
}


function find_or_create_seller_info($name, $image, $online) {

    $r = MYSQL_Q("SELECT * FROM sellerinfo WHERE name='".$name."' AND photo='".$image."'");
    $c = mysql_num_rows($r);

    if ($c == 0) {

        MYSQL_Q("INSERT INTO sellerinfo VALUES ('".$name."', '".$image."', 1, ".($online == true ? '1' : '0').", UNIX_TIMESTAMP(NOW()))");

    } else {

        MYSQL_Q("UPDATE sellerinfo SET count=count+1, online=online+".($online == true ? '1' : '0').
                " WHERE name='".$name."' AND photo='".$image."'");
    }
}


function find_or_create_seller($i) {

    $ref = NULL;

    /*
     * Create the image
     */
    $p = find_or_create_local_seller_image($i['seller_image']);

    /*
     * Create the sellerinfo
     */
    find_or_create_seller_info($i['seller'], $p, $i['online_seller']);

    /*
     * If we have a reference from Google for this seller, then find or create the reference
     */
    if (!empty($i['seller_id']) && $i['seller_id'] != 'null') {
        $ref = find_or_create_reference($i['seller_id'], $i['seller_ref']);
    }

    /*
     * This is an online seller.  We don't store any location for this type of selller. 
     * The location is stored with the deal later on... 
     */
    if ($i['online_seller'] == true) {

        $q = "SELECT * FROM seller WHERE name='".$i['seller']."' AND location IS NULL";
        $r = MYSQL_Q($q);
        $c = mysql_num_rows($r);

        if ($c == 0) {

            $q = "INSERT INTO seller (name, photo, count) VALUES ('%s', '%s', 0)";
            $q = sprintf($q, $i['seller'], $p);
            $r = MYSQL_Q($q);

            return array('id' => mysql_insert_id(), 'count' => 0);

        } else if ($c == 1)  {

            return mysql_fetch_assoc($r);

        } else {

            echo '["Error: 0x0001"]'; die();

        }

    } else if ($ref == NULL) {

        /*
         * TODO: This is a difficult case. The user has given a name of a seller and a location 
         * but has not specified a *specific* seller in a location (e.g. there can be 10 Starbucks 
         * in San Francisco). Right now, we create a new seller entry every time we encounter this. 
         * We will have to comb through such entries and coalesce them together offline 
         */
        $s = $i['seller'];
        $loc = find_or_create_location($i['location'], $i['latitude'], $i['longitude'], 0);
        $q = "INSERT INTO seller (name, location, photo, count) VALUES ('%s', %d, '%s', %d)";
        $q = sprintf($q, $s, $loc, $p, 0);
        $r = MYSQL_Q($q);

        return array('id' => mysql_insert_id(), 'count' => 0);

    } else {
        /*
         * If we have a google places reference, its very easy to look for this place...
         */
        $r = MYSQL_Q("SELECT * FROM seller WHERE reference='".$ref['gid']."'");
        $c = mysql_num_rows($r);

        if ($c == 0) {
            // not found
            $loc = find_or_create_location($ref['location'], $i['latitude'], $i['longitude'], 1);
            $q = "INSERT INTO seller (name, location, photo, reference, count) VALUES ('%s', %d, '%s', '%s', '%s')";
            $q = sprintf($q, $i['seller'], $loc , $p,  $ref['gid'], 0);
            $r = MYSQL_Q($q);

            return array('id' => mysql_insert_id(), 'count' => 0);

        } else if ($c == 1) {
            // found
            return mysql_fetch_assoc($r);
        } else {
            echo '["Error: 0x0001"]'; die();
        }
    }
}

 
?>